TOP

VBA Function: Replace

Description

The VBA REPLACE Function returns the specified number of characters from a character string starting with the defined character number.


REPLACE Syntax

Replace(text, search, replace)

Or

Replace(text, search, replace, start, limit, case)

VBA Replace Example

Perform different replacements in a given string:

Sub ReplaceExample()
    
     text = "www.moonexcel.com.ua"
    
     'Easy replacement
     MsgBox Replace(text, "excel", "sheets")    'Returns: www.moonsheets.com.ua
    
     'Replacement ignoring the first characters
     MsgBox Replace(text, "excel", "sheets", 5) 'Returns: moonsheets.com.ua
    
     'Replacement by defining or not a limit
     MsgBox Replace(text, "e", "E", 5)    'Returns: moonExcEl.com.ua
     MsgBox Replace(text, "e", "E", 5, 1) 'Returns: moonExcel.com.ua
    
     'Replace case sensitive or ignoring
     MsgBox Replace(text, "EXCEL", "sheets")        'Returns: www.moonexcel.com.ua
     MsgBox Replace(text, "EXCEL", "sheets", , , 1) 'Returns: www.moonsheets.com.ua
    
End Sub